/**
 * 
 */
package com.github.sd4324530.fastweixin.api;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.sd4324530.fastweixin.api.config.WxConfig;
import com.github.sd4324530.fastweixin.api.entity.Card;
import com.github.sd4324530.fastweixin.api.enums.CardType;
import com.github.sd4324530.fastweixin.api.response.BaseResponse;
import com.github.sd4324530.fastweixin.api.response.BatchgetCardResponse;
import com.github.sd4324530.fastweixin.api.response.CardCheckStatusResponse;
import com.github.sd4324530.fastweixin.api.response.CreateCardResponse;
import com.github.sd4324530.fastweixin.api.response.GetCardHtmlResponse;
import com.github.sd4324530.fastweixin.api.response.GetSendMessageResponse;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.WxCardMsg;
import com.github.sd4324530.fastweixin.util.BeanUtil;
import com.github.sd4324530.fastweixin.util.JSONUtil;

/**
 * @author TylerChueng
 * @see 微信卡券接口
 * {@linkplain 创建卡劵}
 * {@linkplain 投放卡劵}
 * {@linkplain 核销卡劵}
 * {@linkplain 批量查询卡券列表 }
 * 
 * @version 1.0
 */
public class CardAPI extends BaseAPI {

	public CardAPI(WxConfig config) {
		super(config);
	}

	private static final Logger log = LoggerFactory.getLogger(CardAPI.class);
	
	/**
	 * 卡劵创建
	 * @param card 创建卡劵参数
	 * @return 创建卡劵结果
	 */
	public CreateCardResponse createCard(Card card){
		CreateCardResponse response = null;
		String url = BASE_API_URL + "card/create?access_token=#";
		final Map<String, Object> params = new HashMap<String, Object>();
	    params.put(""+CardType.CARD.toLowerCase()+"", card);
	    log.info("创建卡劵request开始>>>>>");
	    String str = JSONUtil.toJson(params);
	    if(CardType.CASH.equalsIgnoreCase(card.getCard_type())){
	    	 str = str.replace("\""+CardType.BASE.toLowerCase()+"\"", "\""+CardType.CASH.toLowerCase()+"\"");
	    }else if(CardType.GROUPON.equalsIgnoreCase(card.getCard_type())){
	    	 str = str.replace("\""+CardType.BASE.toLowerCase()+"\"", "\""+CardType.GROUPON.toLowerCase()+"\"");
	    }else if(CardType.DISCOUNT.equalsIgnoreCase(card.getCard_type())){
	    	 str = str.replace("\""+CardType.BASE.toLowerCase()+"\"", "\""+CardType.DISCOUNT.toLowerCase()+"\"");
	    }else if(CardType.GIFT.equalsIgnoreCase(card.getCard_type())){
	    	 str = str.replace("\""+CardType.BASE.toLowerCase()+"\"", "\""+CardType.GIFT.toLowerCase()+"\"");
	    }else if(CardType.GENERAL_COUPON.equalsIgnoreCase(card.getCard_type())){
	    	 str = str.replace("\""+CardType.BASE.toLowerCase()+"\"", "\""+CardType.GENERAL_COUPON.toLowerCase()+"\"");
	    }
		BaseResponse r = executePost(url, str);
		log.info("创建卡劵响应>>>>>");
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        log.info("创建卡劵响应结果解析>>>>>");
        response = JSONUtil.toBean(resultJson, CreateCardResponse.class);
		return response;
	}
	
	
	/**
     * 根据openId列表发送卡劵
     * 本方法调用需要账户为微信已认证账户
     * @param message 消息主体
     * @param openIds 群发用户,openId至少2个，否则不会执行
     * @return 群发结果
     */
    public GetSendMessageResponse sendDelivery(BaseMsg message, String[] openIds){
        BeanUtil.requireNonNull(message, "message is null");
        log.debug("群发消息......");
        String url = BASE_API_URL + "cgi-bin/message/mass/send?access_token=#";
        final Map<String, Object> params = new HashMap<String, Object>();
        if(message instanceof WxCardMsg){
        	WxCardMsg msg = (WxCardMsg) message;
        	params.put("msgtype", "wxcard");
            Map<String, String> wxcard = new HashMap<String, String>();
            wxcard.put("card_id", msg.getCard_id());
            params.put("wxcard", wxcard);
            params.put("touser", openIds);
        }
        BaseResponse response = executePost(url, JSONUtil.toJson(params));
        String resultJson = isSuccess(response.getErrcode()) ? response.getErrmsg() : response.toJsonString();
        return JSONUtil.toBean(resultJson, GetSendMessageResponse.class);
    }

	
	public GetCardHtmlResponse getHtml(String cardId){
		GetCardHtmlResponse response = null;
		String url = BASE_API_URL + "card/mpnews/gethtml?access_token=#";
		BaseResponse r = executePost(url, "{\"card_id\":\""+cardId+"\"}");
    	String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        response = JSONUtil.toBean(resultJson, GetCardHtmlResponse.class);
    	return response;
	}
	
	/**
	 * 批量查询卡券列表,用来同步与官方数据一致性
	 * @param offset 查询卡列表的起始偏移量，从0开始，即offset: 5是指从从列表里的第六个开始读取
	 * @param count 需要查询的卡片的数量（数量最大50）
	 * @param statusList(“CARD_STATUS_NOT_VERIFY”,
							待审核；
							“CARD_STATUS_VERIFY_FAIL”,
							审核失败；
							“CARD_STATUS_VERIFY_OK”，
							通过审核；
							“CARD_STATUS_DELETE”，
							卡券被商户删除；
							“CARD_STATUS_DISPATCH”，
							在公众平台投放过的卡券；)
	 * @return
	 */
	public BatchgetCardResponse batchget(int offset,int count,String[] statusList){
		BatchgetCardResponse response = null;
		String url = BASE_API_URL + "card/batchget?access_token=#";
		final Map<String, Object> params = new HashMap<String, Object>();
	    params.put("offset", offset);
	    params.put("count", count);
	    params.put("status_list", statusList);
	    log.info("批量查询卡券列表request开始>>>>>");
	    String str = JSONUtil.toJson(params);
		BaseResponse r = executePost(url, str);
		log.info("批量查询卡券列表响应>>>>>");
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        log.info("批量查询卡券列表响应结果解析>>>>>");
        response = JSONUtil.toBean(resultJson, BatchgetCardResponse.class);
		return response;
	}
	
	/**
	 * 核销卡券
	 * @return 核销卡劵结果
	 */
	public BaseResponse hexiao(String code){
		BaseResponse response = null;
		String url = BASE_API_URL + "card/code/consume?access_token=#";
		final Map<String, Object> params = new HashMap<String, Object>();
	    params.put("code", code);
	    log.info("核销卡劵request开始>>>>>");
	    String str = JSONUtil.toJson(params);
		BaseResponse r = executePost(url, str);
		log.info("核销卡劵响应>>>>>");
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        log.info("核销卡劵响应结果解析>>>>>");
        response = JSONUtil.toBean(resultJson, BaseResponse.class);
		return response;
	}
	
	
	/**
	 * 检查卡券状态
	 * @return 是否可核销
	 */
	public CardCheckStatusResponse checkCode(String code,String cardId){
		CardCheckStatusResponse response = null;
		String url = BASE_API_URL + "card/code/get?access_token=#";
		final Map<String, Object> params = new HashMap<String, Object>();
	    params.put("card_id", cardId);
	    params.put("code", code);
	    params.put("check_consume", true);
	    log.info("查询卡劵状态request开始>>>>>");
	    String str = JSONUtil.toJson(params);
        BaseResponse r = executePost(url, str);
		log.info("查询卡劵状态响应>>>>>");
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        log.info("查询卡劵状态响应结果解析>>>>>");
        response = JSONUtil.toBean(resultJson, CardCheckStatusResponse.class);
		return response;
	}
}
